/*
package com.godtree.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.godtree.util.IdGen;
import com.godtree.dao.RankCompanyMarketCollectMapper;
import com.godtree.model.*;
import com.godtree.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.CharMatcher;
import com.google.common.collect.Lists;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.godtree.constant.Constants.*;

*/
/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lisicheng
 * @since 2022-07-18
 *//*

@Service
@RequiredArgsConstructor
public class RankCompanyMarketCollectServiceImpl extends
    ServiceImpl<RankCompanyMarketCollectMapper, RankCompanyMarketCollect> implements
    IRankCompanyMarketCollectService {

  private final IRanksService ranksService;

  private final IRankItemService rankItemService;

  private final IRankDataService rankDataService;

  private final IRankDropService rankDropService;

  private final IRankScoreService rankScoreService;

  private final IRankCompareService rankCompareService;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void marketValue() {

    Ranks ranks = ranksService.getOne(Wrappers.<Ranks>lambdaQuery().eq(Ranks::getName, "企业市值"));

    if (ranks == null) {
      XxlJobHelper.log("未找到排名【企业市值】");
      return;
    }

    String ranksId = ranks.getId();
    LocalDateTime now = LocalDateTime.now();

    List<RankItem> rankItemList = rankItemService.list(Wrappers.<RankItem>lambdaQuery()
        .eq(RankItem::getRanks, ranksId).eq(RankItem::getDelFlag, ZERO_STR)
        .orderByAsc(RankItem::getSort));

    String defaultRankItemId = rankItemList.stream().findFirst().map(RankItem::getId).orElse("");
    int count = 0;

    while (true) {
      int work = work(ranksId, now, defaultRankItemId, rankItemList);
      if (work == 0) {
        break;
      }
      count += work;
    }

    if (count == 0) {
      XxlJobHelper.log("未更新数据");
      return;
    }

    XxlJobHelper.log("更新排名【企业市值】数据{}条", count);
    // TODO: 2022/7/19 文章更新推送消息
    // 参考：com.jeeplus.modules.rank.data.service.RankDataService#saves
    ranksService.updateKeyWords(ranksId);
    // 更新排名
    for (RankItem rankItem : rankItemList) {
      rankScoreService.updateRankValue(rankItem.getId(), "1".equals(rankItem.getOrderBy()));
    }
    // 更新排名默认分数
    rankDataService.updateDefaultRankScore(ranks.getId());

  }

  @Transactional(rollbackFor = Exception.class)
  public int work(String ranksId, LocalDateTime now, String defaultRankItemId,
      List<RankItem> rankItemList) {

    // 查询一批数据
    List<RankCompanyMarketCollect> list = list(
        Wrappers.<RankCompanyMarketCollect>lambdaQuery().last("limit 100"));

    // 如果查询不到数据了，证明数据被消费完了
    if (CollUtil.isEmpty(list)) {
      return 0;
    }

    // 排名数据
    List<RankData> rankDataList = buildRankData(ranksId, defaultRankItemId, list);

    // 排名列更新维护
    Map<String, String> itemRelation =
        CollUtil.zip(Lists.newArrayList("市值", "股价"),
            Lists.newArrayList("marketVal", "stockPrice"));

    for (RankData rankData : rankDataList) {

      int sort = 1;
      for (String drop : JSONUtil.toList(StrUtil.blankToDefault(rankData.getDrops(), DROP_LIST),
          String.class)) {

        RankDrop rankDrop = RankDrop.builder().ranks(ranksId).sort(sort++).name(drop)
            .delFlag(ZERO_STR).build();
        rankData.getRankDropList().add(rankDrop);

      }

      sort = 1;
      for (RankItem rankItem : rankItemList) {

        boolean first = sort == 1;

        RankScore.RankScoreBuilder rankScoreBuilder =
            RankScore.builder().rankItem(rankItem.getId()).sort(sort++).delFlag(ZERO_STR);

        String filed = itemRelation.get(rankItem.getName());
        if (StrUtil.isBlank(filed)) {
          XxlJobHelper.log("未在【排名列关系】中找到列");
        } else {
          RankCompanyMarketCollect rankCompanyMarketCollect = rankData.getCollect();
          if (rankCompanyMarketCollect == null) {
            XxlJobHelper.log("通过rankData查找rankCompanyMarketCollect失败。rankData:{}；",
                JSONUtil.toJsonStr(rankData));
          }
          String fieldValue = Convert.toStr(
              ReflectUtil.getFieldValue(rankCompanyMarketCollect, filed), "");
          // 根据是否有单位，取单位名称。没有为""
          String unit =
              fieldValue.contains("-") ? fieldValue.substring(fieldValue.lastIndexOf("-") + 1)
                  .trim() : "";
          // 如果有单位，先去掉单位
          if (StrUtil.isNotBlank(unit)) {
            int lastUnitPos = fieldValue.lastIndexOf("-") + 1;
            fieldValue = fieldValue.substring(0, lastUnitPos).replace("-", "").trim();
          }

          BigDecimal rankScore = null;
          // 数据转换
          if (StrUtil.isNotBlank(fieldValue)) {

            // 百分比
            if (PATTERN_REGEX_PERCENT.matcher(fieldValue).matches()) {
              rankScore = new BigDecimal(fieldValue.replace("%", "")).divide(ONE_HUNDRED, 2,
                  RoundingMode.HALF_UP);
            }
            // 时间
            else if (PATTERN_REGEX_TIME.matcher(fieldValue).matches()) {
              String[] split = fieldValue.split(":");
              // 分秒
              if (split.length == 2) {
                rankScore =
                    new BigDecimal(Integer.parseInt(split[0]) * 60 + Integer.parseInt(split[1]));
              }
              // 时分秒
              else if (split.length == 3) {
                rankScore = new BigDecimal(Integer.parseInt(split[0]) * 3600
                    + Integer.parseInt(split[1]) * 60 + Integer.parseInt(split[2]));
              }
            }
            // 数字
            else {
              try {
                rankScore = new BigDecimal(fieldValue);
              } catch (Exception e) {
                XxlJobHelper.log("转换排名数据列为数字失败，fieldValue:{}，异常：{}", fieldValue,
                    ExceptionUtil.stacktraceToString(e));
                rankScore = new BigDecimal(CharMatcher.inRange('0', '9').retainFrom(fieldValue));
              }
            }
          }

          rankScoreBuilder.scoreStr(fieldValue + unit).score(rankScore).rankValue(1);
        }

        RankScore rankScore = rankScoreBuilder.build();
        if (first) {
          rankData.setDefaultRankScoreStr(Convert.toStr(rankScore.getScore(), ""));
          rankData.setDefaultRankValue(rankScore.getRankValue());
        }

        rankData.getRankScoreList().add(rankScore);
      }

    }

    List<String> rankDataIdList = rankDataService.listObjs(
        Wrappers.<RankData>lambdaQuery().eq(RankData::getRanks, ranksId).select(RankData::getId),
        Convert::toStr);

    // 删除数据
    rankDataService.removeBatchByIds(rankDataIdList);
    rankDropService.remove(
        Wrappers.<RankDrop>lambdaQuery().in(RankDrop::getRankData, rankDataIdList));
    rankScoreService.remove(
        Wrappers.<RankScore>lambdaQuery().in(RankScore::getRankData, rankDataIdList));
    rankCompareService.remove(
        Wrappers.<RankCompare>lambdaQuery().in(RankCompare::getRankData, rankDataIdList));

    // 新增数据
    for (RankData rankData : rankDataList) {

      rankData.setId(IdGen.uuid());
      rankData.setCreateDate(now);
      rankData.setUpdateDate(now);
      rankDataService.save(rankData);

      String rankDataId = rankData.getId();

      for (RankDrop rankDrop : rankData.getRankDropList()) {
        rankDrop.setId(IdGen.uuid());
        rankDrop.setRankData(rankDataId);
        rankDropService.save(rankDrop);
      }

      for (RankScore rankScore : rankData.getRankScoreList()) {
        rankScore.setId(IdGen.uuid());
        rankScore.setRankData(rankDataId);
        rankScoreService.save(rankScore);
      }

    }

    // 消费完数据后，删除
    removeBatchByIds(
        list.stream().map(RankCompanyMarketCollect::getId).collect(Collectors.toList()));

    return list.size();
  }

  */
/**
   * 构建排名数据，维护排名数据与原数据的关系
   *
   * @param ranksId           排名id
   * @param defaultRankItemId 默认顶部筛选项id
   * @param list              原数据集合
   * @return 排名数据集合
   *//*

  private List<RankData> buildRankData(String ranksId, String defaultRankItemId,
      List<RankCompanyMarketCollect> list) {
    // 构建排名数据，维护排名数据与原数据的更新
    return list.stream().map(item -> {
      String name = item.getName();
      // 构建排名数据
      return RankData.builder().ranks(ranksId).name(name)
          .fullPinyinName(PinyinUtil.getPinyin(name, ""))
          .simplePinyinName(PinyinUtil.getFirstLetter(name, "")).image(item.getImageUrl())
          .drops(Lists.newArrayList("\"" + item.getCountry() + "\"", "\"\"", "\"\"").stream()
              .collect(Collectors.joining(",", "[", "]")))
          // TODO: 2022/7/19 标签逻辑待完善
          .tags("{}")
          // TODO: 2022/7/19 推荐语值待填充
          .recommendation(null).delFlag(ZERO_STR).showHide(ONE_STR)
          .defaultRankItemId(defaultRankItemId)
          .collect(item).rankDropList(Lists.newArrayList()).rankScoreList(Lists.newArrayList())
          .build();
    }).collect(Collectors.toList());
  }
}
*/
